<template>
	<div class="bind-label">
		<el-dialog :title="dialogTitle" :visible.sync="visible" width="35%" :before-close="closeBindLabel">
			<el-table :data="labelList" border stripe >
			  <el-table-column label="" width="60px" align="center">
				<template slot-scope="scope">
					<el-checkbox v-model="scope.row.selected" @change="onSelectedLabel(scope.row)"></el-checkbox>
				</template>
			  </el-table-column>
			  <el-table-column label="标签名称" prop="name" align="center"></el-table-column>
			  <el-table-column label="创建时间" prop="createdAt" :formatter="formatTime" align="center"></el-table-column>
			</el-table>
			<br />
			<page-size :pages="tablePages"  @changeCurrentPage="changeCurrentPage" @changePageSize="changePageSize"></page-size>
			<span slot="footer" class="dialog-footer">
				<el-button class="close" @click="closeBindLabel">关 闭</el-button>
				<el-button class="sure" @click="sureBindLabel">确 定</el-button>
			</span>
		</el-dialog>
	</div>
</template>

<script>
import PageSize from '@/views/components/PageSize.vue';
import { getBizLabelList, getUserBizLabels, bindBizLabelsToUser } from '@/api/api';

export default {

	components: {
		PageSize
	},

	props: {
		visible: {
			type: Boolean,
			required: true,
			default: () => true
		},

		accountData: {
			type: Object,
			required: true,
			default: () => undefined
		}
	},

	data() {

		return {
			dialogTitle: '',
			showDialog: true,
			labelList: [],
			selectedLabels: [],
			tablePages: {
				total: 0,
				page: 1,
				pageSize: 10
			}
		}
	},

	async mounted() {
		console.log('bind label: mounted, visible: ', this.visible, 'and accountData:', this.accountData);
		this.dialogTitle = `给用户 ${this.accountData.userName} 绑定标签`
		await getUserBizLabels(this.accountData.userId, {page: 1, pageSize: 10000}).then(res => {
				if (res.data && res.data.code === 200){
					if (res.data.data.data && res.data.data.data.length > 0){
						this.selectedLabels = res.data.data.data.map(value => {
							return {...value.bizLabel, selected: true, id: value?.bizLabel?.id | value.labelId};
						});
					}
					console.log('selectedLabels:', this.selectedLabels);
				}
			}).catch(error => {
				console.error('get user labels failure:', error);
			});
		this.refreshLabelList();
	},

	updated() {
		console.log('bind label: updated, visible: ', this.visible, 'and labelData:', this.accountData);
	},

	methods: {
		formatTime(row){
			return this.$moment(row.createdAt).format('YYYY-MM-DD HH:mm:ss');
		},

		closeBindLabel() {
			this.$emit('close');
		},

		sureBindLabel() {
			bindBizLabelsToUser(this.accountData.userId, this.selectedLabels.map(value => {
				return value.id;
			})).then(res => {
				if (res.data && res.data.code == 200){
					this.closeBindLabel();
					this.$message.success('保存成功！');
				}
			}).catch(error => {
				this.$message.error(error);
				// 1301:参数错误； 1101:标签id不存在
			});
		},

		refreshLabelList() {
			getBizLabelList(this.tablePages).then(res => {
				if (res.data && res.data.code === 200){
					this.tablePages.total = res.data.data.count;
					this.labelList = res.data.data.data.map(value => {
						let selected = false;
						for (let i = 0; i < this.selectedLabels.length; i++){
							if (this.selectedLabels[i].id === value.id){
								selected = true;
							}
						}
						return {...value, selected: selected};
					});
					if (this.labelList.length === 0 && this.tablePages.page > 1){
						this.tablePages.page -= 1;
						this.refreshLabelList();
					}
				} 
			});
		},

		changeCurrentPage(page) {
			this.tablePages.page = page;
			this.refreshLabelList();
		},

		changePageSize(pageSize) {
			this.tablePages.pageSize = pageSize;
			this.refreshLabelList();
		},

		onSelectedLabel(row) {
			let hasAdded = false;
			for (let i = 0; i < this.selectedLabels.length; i++){
				if (row.id === this.selectedLabels[i].id){
					hasAdded = true;
					if (!row.selected) {
						this.selectedLabels.splice(i, 1);
					}
					break;
				}
			}
			if (!hasAdded && row.selected){
				this.selectedLabels.push(row);
			}
		}

	}
}
</script>

<style lang="less">
.bind-label {
	.el-dialog__body {
		padding: 10px 20px;
	}
}
</style>

<style lang="less" scoped>
.bind-label {
	.el-button {
		width: 56px;
		height: 32px;
		padding: 0;
		font-size: 14px;
	}
	.close {
		color: #999;
	}
	.sure {
		background-color: #6384fe;
		color: #fff;
	}
	.error {
		position: absolute;
		top: 104px;
		padding-left: 140px;
		color: #ff3b30;
	}
}
</style>